package com.sinopec.yelofixedreader.stock.inn.view

import android.os.Bundle
import android.widget.LinearLayout
import android.widget.TextView
import androidx.activity.result.ActivityResultLauncher
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.jakewharton.rxbinding3.view.clicks
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.sinopec.basemodule.BaseApplication
import com.sinopec.basemodule.adapter.CommonAdapter
import com.sinopec.basemodule.adapter.CustomViewHolder
import com.sinopec.basemodule.base.BaseActivity
import com.sinopec.basemodule.base.CustomToolbar
import com.sinopec.basemodule.model.StockInListModel
import com.sinopec.basemodule.utils.ARouterManagerUtils
import com.sinopec.yelofixedreader.stock.inn.R
import com.sinopec.yelofixedreader.stock.inn.contract.StockInListContract
import com.sinopec.yelofixedreader.stock.inn.presenter.StockInListPresenter
import com.sinopec.yelofixedreader.stock.inn.resultcontract.RFIDIn
import io.reactivex.android.schedulers.AndroidSchedulers
import kotlinx.android.synthetic.main.activity_stock_in_order_list.*
import java.util.concurrent.TimeUnit

/**
 * @author lwj
 * @ClassName: StockInListActivity
 * @Description: 入库列表
 */
@Route(path = ARouterManagerUtils.GOTO_IN_STOCK_IN_LIST_ACTIVITY)
class StockInListActivity : BaseActivity<StockInListPresenter>(), StockInListContract.View {

    private var launcherInScan: ActivityResultLauncher<RFIDIn.Params>? = null

    //列表适配器
    private var datas = arrayListOf<StockInListModel>()
    private var adapter: CommonAdapter<StockInListModel>? = null
    private var linearLayoutManager: LinearLayoutManager? = null

    override fun getContentView(): Int {
        return R.layout.activity_stock_in_order_list
    }

    override fun configToolbar(rToolbar: CustomToolbar) {
        //配置标题
        rToolbar.setToolbarVisible(false)
    }

    override fun onResume() {
        super.onResume()
        if (mPresenter != null) {
            srl.autoRefresh()
        }
    }

    override fun initView(savedInstanceState: Bundle?) {
        mPresenter = StockInListPresenter(this)
        val userInfo = BaseApplication.getInstance().userManager.user
        //设备id
        tv_device_id.text = userInfo.deviceId
        //仓库
        tv_warehouse.text = userInfo.stockWarehouseName
        //登录用户
        tv_name.text = userInfo.userAccount

        linearLayoutManager = LinearLayoutManager(mContext)
        rv_list.layoutManager = linearLayoutManager
        //rv_list.addItemDecoration(SpaceItemDecoration(10, 0))
        //srl.autoRefresh()
        srl.setEnableLoadMore(false)
        //刷新控件
        srl.setOnRefreshListener { refreshlayout: RefreshLayout ->
            mPresenter.searchList("")
            refreshlayout.finishRefresh()
        }
        srl.setOnLoadMoreListener { refreshlayout: RefreshLayout ->
            mPresenter.searchList("")
            refreshlayout.finishLoadMore()
        }

        //列表适配器
        adapter = object :
            CommonAdapter<StockInListModel>(mContext, R.layout.item_stock_in_order_list, datas) {
            override fun convert(
                holder: CustomViewHolder,
                model: StockInListModel,
                position: Int,
            ) {
                val itemView = holder.itemView

                //序号
                val tv_serial_number = holder.getView<TextView>(R.id.tv_serial_number)
                tv_serial_number.text = (position + 1).toString()
                //任务ID
                val tv_taskRecordId = holder.getView<TextView>(R.id.tv_taskRecordId)
                tv_taskRecordId.text = model.taskRecordId?.toString()
                //任务单号
                val tv_taskNo = holder.getView<TextView>(R.id.tv_taskNo)
                tv_taskNo.text = model.taskNo?.ifEmpty { "--" }
                //仓库名称-库位名称
                val tv_locationName = holder.getView<TextView>(R.id.tv_locationName)
                tv_locationName.text = model.locationName?.ifEmpty { "--" }
                //物料名称
                val tv_mtrlName = holder.getView<TextView>(R.id.tv_mtrlName)
                tv_mtrlName.text = model.mtrlName?.ifEmpty { "--" }
                //机器码
                val tv_machineCode = holder.getView<TextView>(R.id.tv_machineCode)
                tv_machineCode.text = model.machineCode?.ifEmpty { "--" }
                //预计总重量（吨）
                val tv_expectedPalletQuantity =
                    holder.getView<TextView>(R.id.tv_expectedPalletQuantity)
                tv_expectedPalletQuantity.text = model.expectedPalletQuantity.toString()
                //任务优先级
                val tv_taskPriority = holder.getView<TextView>(R.id.tv_taskPriority)
                tv_taskPriority.text = model.taskPriority.toString()

                /**
                 *  扫码入库
                 */
                val ll_stock_in = holder.getView<LinearLayout>(R.id.ll_stock_in)
                addDisposable(ll_stock_in.clicks()
                    .throttleFirst(1, TimeUnit.SECONDS)
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe {
                        launcherInScan?.launch(
                            RFIDIn.Params(
                                model
                            )
                        )
                    })

                /**
                 *  详情
                 */
                addDisposable(itemView.clicks()
                    .throttleFirst(1, TimeUnit.SECONDS)
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe {
                        ARouterManagerUtils.gotoStockInDetail(model)
                    })
            }
        }
        rv_list.adapter = adapter


    }

    override fun initEvent() {
        super.initEvent()

        launcherInScan = registerForActivityResult(RFIDIn) {
            //扫码结果
            if (it?.codeResult == RFIDIn.Result.CODE_FINISH_AND_OPEN_DETAIL) {
            }
        }

        /**
         *  返回
         */
        addDisposable(ll_back.clicks()
            .throttleFirst(1, TimeUnit.SECONDS)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe {
                finish()
            }
        )
    }

    /**
     * 列表
     */
    override fun refreshUI(list: List<StockInListModel>) {
        datas.clear()
        datas.addAll(list)
        adapter?.notifyDataSetChanged()
    }
}

